package com.yeskery.nut.view.thymeleaf;

import com.yeskery.nut.extend.i18n.MessageService;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.messageresolver.AbstractMessageResolver;

/**
 * Nut消息转换器
 * @author YESKERY
 * 2023/11/10
 */
public class NutMessageResolver extends AbstractMessageResolver {

    /** 国际化消息服务 */
    private final MessageService messageService;

    /**
     * 构建Nut消息转换器
     * @param messageService 国际化消息服务
     */
    public NutMessageResolver(MessageService messageService) {
        this.messageService = messageService;
    }

    @Override
    public String resolveMessage(ITemplateContext context, Class<?> origin, String key, Object[] messageParameters) {
        return messageService.getMessage(key, messageParameters);
    }

    @Override
    public String createAbsentMessageRepresentation(ITemplateContext context, Class<?> origin, String key, Object[] messageParameters) {
        if (context.getLocale() != null) {
            return "??" + key + "_" + context.getLocale().toString() + "??";
        }
        return "??" + key + "_" + "??";
    }
}
